<?php


class SQLDatabase {
	
	protected $link;
        protected $t_prefix;
	
	public function __construct($database, $user, $password, $host='localhost', $table_prefix='lt_') {
		$this->link = new PDO(
					"mysql:host=$host;dbname=$database", 
					$user, $password
		);
		$this->link->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

                $this->t_prefix = $table_prefix;
	}
	
}

/**
 * Use:
 * 	Add constants to subclasses to define the ATTRIBUTES (columns) of a record:
 * 		const <database column> = '<database column>';  => MUST BE THE SAME!
 */
class Entity {
	
	// Should be private, but at the moment we would like to use json_encode for encoding objects, which doesn't work if the data is private.
	public $data;
	
	public function __construct($data) {
		$this->get_attribute_names(true);
		$this->update($data);
	}
	
	public function get_attribute_names($check=false) {
		$cls = get_class($this);
		$reflect = new ReflectionClass($cls);
		if ($check) {
			foreach ($reflect->getConstants() as $constant) {
				if ($reflect->getConstant($constant) != $constant) {
					throw new Exception("Problem for $cls::$constant: name and value must be equal");
				}
			}
		}
		return $reflect->getConstants();
	}
    
    public function __get($name) {
    	if (isset($this->data[$name])) {
    		return $this->data[$name];
    	}
    	else {
    		throw new Exception("$name attribute is not assigned yet.");
    	}
    }
    
    public function __set($name, $value) {
    	if ( ! in_array($name, $this->get_attribute_names()) ) {
    		if (defined('DEBUG') and DEBUG) {
    			var_dump($this);
    		}
    		throw new Exception("The '$name' attribute is not defined!");
    	}
    	$this->data[$name] = $value;  
    }
    
    public function update($data) {
    	foreach ($data as $name => $value) {
    		$this->$name = $value;
    	}
    }
    
    public function get_data() {
    	return $this->data;
    }
	
}